﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Classes;
using VAdvantage.Logging;
using VAdvantage.Utility;
using VAdvantage.Model;
using SLControls.Controls;
using SilverlightDesktop.Controls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using VAdvantage.DataBase;
using VAdvantage.Framework;
using System.Collections;

namespace VAdvantage.Search
{
    public partial class PAttributeInstance : ChildWindow
    {
        public PAttributeInstance()
        {
            InitializeComponent();
        }

        #region private variables


        //	Parameter
        private int _M_Warehouse_ID;
        private int _M_Locator_ID;
        private int _M_Product_ID;
        private int _M_AttributeSetInstance_ID = -1;
        private String _M_AttributeSetInstanceName = null;
        private String _sql;
        //Lauout set in prepareTable and used in loadTable   
        private Info_Column[] m_layout = null;
        // Multi Selection mode (default false) 
        private bool m_multiSelection = false;
        //Model Index of Key Column   
        private int _keyColumnIndex = -1;
        //Logger			
        private static VLogger log = VLogger.GetVLogger(typeof(PAttributeInstance).FullName);
        //protected VDataGridView.VDataGridView vdgvRecords = new VDataGridView.VDataGridView();
        // protected DataGrid vdgvRecords = new DataGrid();
        //Table Column Layout Info//here change from Info_Column-Info_Column
        private static Info_Column[] s_layout = new Info_Column[] 
	{
		new Info_Column("ID", "s.M_AttributeSetInstance_ID", typeof(IDColumn)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "Description"), "asi.Description", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "Lot"), "asi.Lot", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "SerNo"), "asi.SerNo", typeof(String)), 
		new Info_Column(Msg.Translate(Envs.GetContext(), "GuaranteeDate"), "asi.GuaranteeDate", typeof(DateTime)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "M_Locator_ID"), "l.Value", typeof(KeyNamePair), "s.M_Locator_ID"),
		new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOnHand"), "s.QtyOnHand", typeof(Double)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "QtyReserved"), "s.QtyReserved", typeof(Double)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "QtyOrdered"), "s.QtyOrdered", typeof(Double)),
		//	See RV_Storage
		//jz new Info_Column(Msg.Translate(Env.GetContext(), "GoodForDays"), "(TRUNC(asi.GuaranteeDate,'DD')-TRUNC(SysDate,'DD'))-p.GuaranteeDaysMin", Integer.class, true, true, null),
		//new Info_Column(Msg.Translate(Env.GetContext(), "ShelfLifeDays"), "TRUNC(asi.GuaranteeDate,'DD')-TRUNC(SysDate,'DD')", Integer.class),
		new Info_Column(Msg.Translate(Envs.GetContext(), "GoodForDays"), "daysBetween(TRUNC(asi.GuaranteeDate,'DD'),TRUNC(SysDate,'DD'))-p.GuaranteeDaysMin", typeof(int), true, true, null),
		new Info_Column(Msg.Translate(Envs.GetContext(), "ShelfLifeDays"), "daysBetween(TRUNC(asi.GuaranteeDate,'DD'),TRUNC(SysDate,'DD'))", typeof(int)),
		//jz new Info_Column(Msg.Translate(Env.GetContext(), "ShelfLifeRemainingPct"), "CASE WHEN p.GuaranteeDays > 0 THEN TRUNC(((TRUNC(asi.GuaranteeDate,'DD')-TRUNC(SysDate,'DD'))/p.GuaranteeDays)*100) ELSE 0 END", Integer.class),
		new Info_Column(Msg.Translate(Envs.GetContext(), "ShelfLifeRemainingPct"), "CASE WHEN p.GuaranteeDays > 0 THEN daysBetween(TRUNC(asi.GuaranteeDate,'DD'),TRUNC(SysDate,'DD'))/p.GuaranteeDays*100 ELSE 0 END", typeof(int)),
	};
        //	From Clause						
        private static String s_sqlFrom = "M_Storage s"
            + " INNER JOIN M_Locator l ON (s.M_Locator_ID=l.M_Locator_ID)"
            + " INNER JOIN M_Product p ON (s.M_Product_ID=p.M_Product_ID)"
            + " LEFT OUTER JOIN M_AttributeSetInstance asi ON (s.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID)";
        // Where Clause						
        //private static String s_sqlWhere = "l.M_Warehouse_ID=@M_Warehouse_ID AND s.M_Product_ID=@M_Product_ID";
        private static String s_sqlWhere = " s.M_Product_ID=@M_Product_ID";

        private String _sqlNonZero = " AND (s.QtyOnHand<>0 OR s.QtyReserved<>0 OR s.QtyOrdered<>0)";

        //************Controls added through design****
        // private Panel pnlbottum;
        //private TableLayoutPanel tbplMain;
        //private TableLayoutPanel tbplBottum;
        //private ImageButton btnok;
        //private ImageButton btnCancel;
        //private Panel tbplMain;
        //private Panel tbplBottum;
        //private VImage btnok;
        //private VImage btnCancel;

        // private VAdvantage.Controls.VCheckBox chkShowAll;
        private String _sqlMinLife = "";
        //object[] finalData = null;
        DataRow finalData = null;

        #endregion

        /// <summary>
        ///Constructor
        /// </summary>
        /// <param name="parent">dialog parent</param>
        /// <param name="title">title</param>
        /// <param name="M_Warehouse_ID">warehouse key name pair</param>
        /// <param name="M_Locator_ID">locator</param>
        /// <param name="M_Product_ID">product key name pair</param>
        /// <param name="C_BPartner_ID">bp</param>
        public PAttributeInstance(Form parent, String title,
            int M_Warehouse_ID, int M_Locator_ID, int M_Product_ID, int C_BPartner_ID)
        //: base(true, true, true, true, true, Msg.GetMsg(Env.GetContext(), "PAttributeInstance") + title)
        {
            InitializeComponent();
            Init(M_Warehouse_ID, M_Locator_ID, M_Product_ID, C_BPartner_ID);
            //vdgvRecords.Click += new EventHandler(vdgvRecords_Click);
            this.chkShowAll.Content = Msg.GetMsg(Envs.GetContext(), "ShowAll");

        }

        /// <summary>
        /// Initialization
        /// </summary>
        /// <param name="M_Warehouse_ID">wh</param>
        /// <param name="M_Locator_ID">loc</param>
        /// <param name="M_Product_ID"> product</param>
        /// <param name="C_BPartner_ID">partner</param>
        private void Init(int M_Warehouse_ID, int M_Locator_ID, int M_Product_ID, int C_BPartner_ID)
        {
            _M_Warehouse_ID = M_Warehouse_ID;
            _M_Locator_ID = M_Locator_ID;
            _M_Product_ID = M_Product_ID;
            try
            {
                // JbInit();
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    DynInit(C_BPartner_ID);
                });
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
        }

        /// <summary>
        /// Static Init
        /// </summary>
        //private void JbInit()
        //{
        //    //check box setting
        //    // this.chkShowAll = new VAdvantage.Controls.VCheckBox();

        //    // 
        //    // chkShowAll
        //    // 
        //    // this.chkShowAll.Anchor = System.Windows.Forms.AnchorStyles.Right;
        //    // this.chkShowAll.AutoSize = true;
        //    // this.chkShowAll.Location = new System.Drawing.Point(581, 11);
        //   // this.chkShowAll.Name = "chkShowAll";
        //    // this.chkShowAll.Size = new System.Drawing.Size(80, 17);
        //   // this.chkShowAll.TabIndex = 0;
        //    this.chkShowAll.Content = Msg.GetMsg(Envs.GetContext(), "ShowAll");
        //    //this.chkShowAll.UseVisualStyleBackColor = true;
        //    this.tbplMain.Controls.Add(this.chkShowAll, 0, 0);

        //    //Grid setting

        //    this.tbplMain.Controls.Add(this.vdgvRecords, 0, 1);
        //    this.vdgvRecords.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        //    this.vdgvRecords.Dock = System.Windows.Forms.DockStyle.Fill;
        //    this.vdgvRecords.Location = new System.Drawing.Point(0, 48);
        //    this.vdgvRecords.Margin = new System.Windows.Forms.Padding(0);
        //    CommonFunctions.SetDataGridPrperties(vdgvRecords);

        //    this.chkShowAll.CheckedChanged += new System.EventHandler(this.showAll_CheckedChanged);

        //}

        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <param name="C_BPartner_ID">BP</param>
        private void DynInit(int C_BPartner_ID)
        {
            log.Config("C_BPartner_ID=" + C_BPartner_ID);
            if (C_BPartner_ID != 0)
            {
                int shelfLifeMinPct = 0;
                int shelfLifeMinDays = 0;
                String sql = "SELECT bp.ShelfLifeMinPct, bpp.ShelfLifeMinPct, bpp.ShelfLifeMinDays "
                    + "FROM C_BPartner bp "
                    + " LEFT OUTER JOIN C_BPartner_Product bpp"
                    + " ON (bp.C_BPartner_ID=bpp.C_BPartner_ID AND bpp.M_Product_ID=" + _M_Product_ID + ") "
                    + "WHERE bp.C_BPartner_ID=" + C_BPartner_ID;
                IDataReader idr = null;
                try
                {
                    idr = DataBase.DB.ExecuteReader(sql, null, null);
                    if (idr.Read())
                    {

                        shelfLifeMinPct = Utility.Util.GetValueOfInt(idr[0]);		//	BP
                        int pct = Utility.Util.GetValueOfInt(idr[1]);				//	BP_P
                        if (pct > 0)	//	overwrite
                        {
                            shelfLifeMinDays = pct;
                        }
                        shelfLifeMinDays = Utility.Util.GetValueOfInt(idr[2]);
                    }
                    idr.Close();
                }
                catch (Exception e)
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
                if (shelfLifeMinPct > 0)
                {
                    //jz daysbetween???
                    //_sqlMinLife = " AND COALESCE(TRUNC(((TRUNC(asi.GuaranteeDate,'DD')-TRUNC(SysDate,'DD'))/p.GuaranteeDays)*100),0)>=" + ShelfLifeMinPct;
                    _sqlMinLife = " AND COALESCE(TRUNC((daysBetween(TRUNC(asi.GuaranteeDate,'DD'),TRUNC(SysDate,'DD'))/p.GuaranteeDays)*100),0)>=" + shelfLifeMinPct;
                    log.Config("PAttributeInstance.dynInit - ShelfLifeMinPct=" + shelfLifeMinPct);
                }
                if (shelfLifeMinDays > 0)
                {
                    //jz _sqlMinLife += " AND COALESCE((TRUNC(asi.GuaranteeDate,'DD')-TRUNC(SysDate,'DD')),0)>=" + ShelfLifeMinDays;
                    _sqlMinLife += " AND COALESCE(daysBetween(TRUNC(asi.GuaranteeDate,'DD'),TRUNC(SysDate,'DD')),0)>=" + shelfLifeMinDays;
                    log.Config("PAttributeInstance.dynInit - ShelfLifeMinDays=" + shelfLifeMinDays);
                }
            }	//	BPartner != 0

            //Fill Grid*************>>
            //_sql = PrepareTable(s_layout, s_sqlFrom, s_sqlWhere, false, "s") + " ORDER BY asi.GuaranteeDate, s.QtyOnHand";	//	oldest, smallest first
            _sql = PrepareTable(s_layout, s_sqlFrom, s_sqlWhere, false, "s") + " ORDER BY asi.GuaranteeDate, s.QtyOnHand";	//	oldest, smallest first

            Dispatcher.BeginInvoke(delegate
            {
                Refresh();
            });
        }

        /// <summary>
        /// Prepare Table and return SQL
        /// </summary>
        /// <param name="layout">array of column info</param>
        /// <param name="from">SQL FROM content</param>
        /// <param name="where">SQL WHERE content</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="tableName">table name</param>
        /// <returns>SQL</returns>
        public String PrepareTable(Info_Column[] layout, String from, String where, bool multiSelection, String tableName)
        {
            m_layout = layout;
            m_multiSelection = multiSelection;
            //
            StringBuilder sql = new StringBuilder("SELECT ");
            //  add columns & sql
            for (int i = 0; i < layout.Length; i++)
            {
                //  create sql
                if (i > 0)
                {
                    sql.Append(", ");
                }
                sql.Append(layout[i].GetColSQL());
                //  adding ID column
                //if (layout[i].isKeyPairCol())
                if (layout[i].IsIDcol())
                {
                    //sql.Append(",").Append(layout[i].getKeyPairColSQL());
                    sql.Append(",").Append(layout[i].GetIDcolSQL());
                }

                //  add to model
                //addColumn(layout[i].GetColHeader());//*************//
                //if (layout[i].IsColorColumn())
                //{
                //     setColorColumn(i);
                //}

                if (layout[i].GetColClass() == typeof(IDColumn))
                {
                    _keyColumnIndex = i;
                }

            }
            //  set editors (two steps)
            //for (int i = 0; i < layout.Length; i++)
            //{

            //     setColumnClass(i, layout[i].getColClass(), layout[i].isReadOnly(), layout[i].getColHeader());
            //}

            sql.Append(" FROM ").Append(from);
            sql.Append(" WHERE ").Append(where);

            //*************** Change *************
            if (_M_Locator_ID != 0)
            {
                sql.Append(" AND s.M_Locator_ID = " + _M_Locator_ID);
            }

            //  Table Selection
            //setRowSelectionAllowed(true);
            
            if (from.Length == 0)
            {
                return sql.ToString();
            }
            //
            String finalSQL = MRole.GetDefault().AddAccessSQL(sql.ToString(),
                tableName, MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
            log.Finest(finalSQL);
            return finalSQL;
        }

        /// <summary>
        /// Refresh Query
        /// </summary>
        private void Refresh()
        {
            if (_sql == null)
            {
                _sql = "";
            }
            String sql = _sql;
            int pos = _sql.LastIndexOf(" ORDER BY ");
            if ((bool)!chkShowAll.IsChecked)
            {
                sql = _sql.Substring(0, pos) + _sqlNonZero;
                if (_sqlMinLife.Length > 0)
                {
                    sql += _sqlMinLife;
                }
                sql += _sql.Substring(pos);
            }
            //
            log.Finest(sql);

            try
            {

                SqlParameter[] param = new SqlParameter[1];
                //param[0] = new SqlParameter("@M_Warehouse_ID", _M_Warehouse_ID);
                param[0] = new SqlParameter("@M_Product_ID", _M_Product_ID);
                DataSet ds = null;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    ds = DB.ExecuteDataset(sql, param, null);
                    Dispatcher.BeginInvoke(delegate
                    {
                        //finalData = new object[s_layout.Length];

                        DataTable dt = new DataTable();
                        if (ds == null)
                        {
                            log.Log(Level.SEVERE, sql, "");
                        }
                        else
                        {
                            vdgvRecords.Columns.Clear();
                            vdgvRecords.AutoGenerateColumns = false;
                            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                            {
                                finalData = new DataRow(dt);
                                int colOffset = 0;  //  columns start with 1
                                for (int col = 0; col < s_layout.Length; col++)
                                {
                                    Object data = null;

                                    Type c = s_layout[col].GetColClass();
                                    int colIndex = col + colOffset;

                                    //if (col == 0)
                                    //{

                                    //    s_layout[col].SetColHeader(s_layout[col].GetColHeader() + "_ID");
                                    //}
                                    if (i == 0)
                                    {
                                        if (c == typeof(DateTime))
                                        {
                                            // dt.Columns.Add(s_layout[col].GetColHeader(), typeof(string));   //n
                                            DataColumn column = new DataColumn(s_layout[col].GetColHeader(), typeof(string));
                                            dt.Columns.Add(column);   //n


                                            //DataGridTextColumn dgcol = new DataGridTextColumn();
                                            //dgcol.Binding = new System.Windows.Data.Binding(dt.Columns[col].ColumnName);
                                            //dgcol.Header = dt.Columns[col].ColumnName;
                                            //vdgvRecords.Columns.Add(dgcol);
                                        }
                                        else
                                        {
                                            // dt.Columns.Add(s_layout[col].GetColHeader(), c);   //n
                                            DataColumn column = new DataColumn(s_layout[col].GetColHeader(), c);
                                            dt.Columns.Add(column);   //n
                                            if (c == typeof(KeyNamePair))
                                            {
                                                DataColumn column1 = new DataColumn("Locator_ID", typeof(int));
                                                dt.Columns.Add(column1);
                                            }


                                            //DataGridTextColumn dgcol = new DataGridTextColumn();
                                            //dgcol.Binding = new System.Windows.Data.Binding(dt.Columns[col].ColumnName);
                                            //dgcol.Header = dt.Columns[col].ColumnName;
                                            //vdgvRecords.Columns.Add(dgcol);
                                        }
                                    }
                                    if (c == typeof(IDColumn))
                                    {
                                        data = new IDColumn(Utility.Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString()));
                                        // finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);

                                    }
                                    else if (c == typeof(Boolean))
                                    {
                                        data = "Y".Equals(ds.Tables[0].Rows[i][colIndex].ToString());
                                        // finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                    }
                                    else if (c == typeof(DateTime))
                                    {
                                        if (ds.Tables[0].Rows[i][colIndex].ToString() != "")
                                        {
                                            data = DateTime.Parse(ds.Tables[0].Rows[i][colIndex].ToString());
                                            /// finalData[col] = data;
                                            finalData.AddDataField(col);
                                            finalData.SetValue(col, data);

                                        }
                                        else
                                        {
                                            data = "";
                                            // finalData[col] = data;
                                            finalData.AddDataField(col);
                                            finalData.SetValue(col, data);
                                        }
                                    }
                                    else if (c == typeof(Decimal))
                                    {
                                        data = Utility.Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                                        //finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                    }
                                    else if (c == typeof(Double))
                                    {
                                        data = Utility.Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                                        //finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                    }
                                    else if (c == typeof(Int32))
                                    {
                                        data = Utility.Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString());
                                        //finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                    }
                                    else if (c == typeof(KeyNamePair))
                                    {
                                        Object display = ds.Tables[0].Rows[i][colIndex].ToString();
                                        int key = ds.Tables[0].Rows[i][colIndex].ToString() != "" ? Utility.Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex + 1].ToString()) : 0;
                                        data = new KeyNamePair(key, display.ToString());
                                        //finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                        finalData.AddDataField(col + 1); col++;
                                        finalData.SetValue(col, key);
                                        colOffset++;
                                    }
                                    else
                                    {
                                        data = ds.Tables[0].Rows[i][colIndex].ToString();
                                        //finalData[col] = data;
                                        finalData.AddDataField(col);
                                        finalData.SetValue(col, data);
                                    }
                                }

                                dt.Rows.Add(finalData);

                            }

                            //for (int i = 0; i < s_layout.Length; i++)
                            //{
                            //    DataGridTextColumn dgcol = new DataGridTextColumn();

                            //    DataColumn dcol = new DataColumn(s_layout[i].GetColHeader());

                            //    dt.Columns.Add(dcol);


                            //    dgcol.Binding = new System.Windows.Data.Binding(dt.Columns[i].ColumnName);
                            //    dgcol.Header = dt.Columns[i].ColumnName;
                            //    vdgvRecords.Columns.Add(dgcol);

                            //}
                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                DataGridTextColumn dgcol = new DataGridTextColumn();
                                dgcol.Binding = new System.Windows.Data.Binding(dt.Columns[i].ColumnName);
                                dgcol.Header = dt.Columns[i].ColumnName;
                                vdgvRecords.Columns.Add(dgcol);

                            }

                            ds.Dispose();
                            ds = null;
                        }

                        //m_table.loadTable(rs);
                        //Load DataGrid
                        //vdgvRecords.DataSource = dt;
                        vdgvRecords.ItemsSource = dt.GetBindableData(new Connector());
                        if (vdgvRecords.Columns.Count > 0)
                            vdgvRecords.Columns[0].Visibility = Visibility.Collapsed;// false;
                        vdgvRecords.IsReadOnly = true;
                        EnableButtons();
                    });
                });


            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
            }

        }

        /// <summary>
        /// Table selection changed
        /// </summary>
        //private void vdgvRecords_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        //int index = vdgvRecords.SelectedRows[0].Index;
        //        int index = vdgvRecords.SelectedIndex;
        //    }
        //    catch { }
        //    EnableButtons();
        //}

        /// <summary>
        /// check box click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void chkShowAll_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        /// <summary>
        /// Enable/Set Buttons and set ID
        /// </summary>
        private void EnableButtons()
        {
            int row = -1;
            IList rowSource = vdgvRecords.ItemsSource as IList;
            try
            {
                //row = vdgvRecords.SelectedRows[0].Index;
                row = vdgvRecords.SelectedIndex;
            }
            catch
            {

            }
            //first time select row 0(-1)
            _M_AttributeSetInstance_ID = -1;
            _M_AttributeSetInstanceName = null;
            _M_Locator_ID = 0;
            bool enabled = row != -1;
            if (enabled)
            {
                //int ID = m_table.getSelectedRowKey();
                int? ID = GetSelectedRowKey();

                if (ID != null)
                {
                    _M_AttributeSetInstance_ID = Utility.Util.GetValueOfInt(ID);
                    //m_M_AttributeSetInstanceName = (String)m_table.getValueAt(row, 1);
                    //_M_AttributeSetInstanceName =  (String)vdgvRecords.Rows[row].Cells[1].Value;

                    _M_AttributeSetInstanceName = ((BindableObject)rowSource[vdgvRecords.SelectedIndex]).GetValue(1);
                    //Object oo = m_table.getValueAt(row, 5);
                    // Object oo =  vdgvRecords.Rows[row].Cells[5].Value;
                    object oo = ((BindableObject)rowSource[vdgvRecords.SelectedIndex]).GetValue(6);

                    _M_Locator_ID = Convert.ToInt32(oo);
                    // KeyNamePair aa = (KeyNamePair) s_layout[5];
                    // Type c = s_layout[5].GetColClass();
                    //if (oo is KeyNamePair)
                    //if(c == typeof(KeyNamePair))
                    //{
                    //    KeyNamePair pp = (KeyNamePair)oo;
                    //    _M_Locator_ID = pp.GetKey();
                    //}
                }
            }
            btnok.IsEnabled = enabled;
            if (!btnok.IsEnabled)
            {
                //this.btnok.NormalImage = global::VAdvantage.Properties.Resources.BtnDisable;
            }
            else
            {
                // this.btnok.NormalImage = global::VAdvantage.Properties.Resources.right_up;
            }
            log.Fine("M_AttributeSetInstance_ID=" + _M_AttributeSetInstance_ID
                + " - " + _M_AttributeSetInstanceName
                + "; M_Locator_ID=" + _M_Locator_ID);
        }

        /// <summary>
        /// Gets the selected row key from data grid view.
        /// </summary>
        /// <returns></returns>
        protected int? GetSelectedRowKey()
        {
            //int row = vdgvRecords.SelectedRows[0].Index;
            int row = vdgvRecords.SelectedIndex;
            IList rowSourcce = vdgvRecords.ItemsSource as IList;
            // DataGridRow dgr=(DataGridRow)vdgvRecords.SelectedItem;
            if (row != -1 && _keyColumnIndex != -1)
            {
                //Object data =  vdgvRecords.Rows[row].Cells[_keyColumnIndex].Value;
                //vdgvRecords.


                //object _data=  ((TextBlock)vdgvRecords.CurrentColumn.GetCellContent((DataGridRow)vdgvRecords.SelectedItem)).Text;
                //object data=vdgvRecords.Columns[_keyColumnIndex].GetCellContent(vdgvRecords.SelectedItem);


                //FrameworkElement result = GetParent(fe, typeof(DataGridCell));
                string obj = ((BindableObject)rowSourcce[vdgvRecords.SelectedIndex]).GetValue(_keyColumnIndex);
                int index = obj.IndexOf(',');
                obj = obj.Substring(index - 7, 7);
                return Convert.ToInt32(obj);

                //if (data.GetType() == typeof(IDColumn))
                //{
                //    data = ((IDColumn)data).GetRecord_ID();
                //    return Utility.Util.GetValueOfInt(data); 
                //}
                //else if (data.GetType() == typeof(Int32))
                //{
                //    return (int)data;
                //}
                //else if (data.GetType() == typeof(Decimal))
                //{
                //    return Utility.Util.GetValueOfInt(data);
                //}
            }
            return -1;
        }

        /// <summary>
        /// Get Attribute Set Instance
        /// </summary>
        /// <returns>M_AttributeSetInstance_ID or -1</returns>
        public int GetM_AttributeSetInstance_ID()
        {
            return _M_AttributeSetInstance_ID;
        }

        /// <summary>
        /// Get Instance Name
        /// </summary>
        /// <returns>Instance Name</returns>
        public String GetM_AttributeSetInstanceName()
        {
            return _M_AttributeSetInstanceName;
        }

        /// <summary>
        /// Get Locator
        /// </summary>
        /// <returns>M_Locator_ID or 0</returns>
        public int GetM_Locator_ID()
        {
            return _M_Locator_ID;
        }

        /// <summary>
        /// Design
        /// </summary>
        //private void InitializeComponent()
        //{
        //    this.pnlbottum = new System.Windows.Forms.Panel();
        //    this.tbplBottum = new System.Windows.Forms.TableLayoutPanel();
        //    this.btnCancel = new System.Windows.Forms.ImageButton();
        //    this.btnok = new System.Windows.Forms.ImageButton();
        //    this.tbplMain = new System.Windows.Forms.TableLayoutPanel();
        //    this.pnlbottum.SuspendLayout();
        //    this.tbplBottum.SuspendLayout();
        //    ((System.ComponentModel.ISupportInitialize)(this.btnCancel)).BeginInit();
        //    ((System.ComponentModel.ISupportInitialize)(this.btnok)).BeginInit();
        //    this.SuspendLayout();
        //    // 
        //    // pnlbottum
        //    // 
        //    this.pnlbottum.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        //    this.pnlbottum.Controls.Add(this.tbplBottum);
        //    this.pnlbottum.Dock = System.Windows.Forms.DockStyle.Bottom;
        //    this.pnlbottum.Location = new System.Drawing.Point(0, 349);
        //    this.pnlbottum.Name = "pnlbottum";
        //    this.pnlbottum.Size = new System.Drawing.Size(664, 45);
        //    this.pnlbottum.TabIndex = 1;
        //    // 
        //    // tbplBottum
        //    // 
        //    this.tbplBottum.ColumnCount = 3;
        //    this.tbplBottum.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        //    this.tbplBottum.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));
        //    this.tbplBottum.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));
        //    this.tbplBottum.Controls.Add(this.btnCancel, 1, 0);
        //    this.tbplBottum.Controls.Add(this.btnok, 2, 0);
        //    this.tbplBottum.Dock = System.Windows.Forms.DockStyle.Fill;
        //    this.tbplBottum.Location = new System.Drawing.Point(0, 0);
        //    this.tbplBottum.Name = "tbplBottum";
        //    this.tbplBottum.RowCount = 1;
        //    this.tbplBottum.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
        //    this.tbplBottum.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 43F));
        //    this.tbplBottum.Size = new System.Drawing.Size(662, 43);
        //    this.tbplBottum.TabIndex = 0;
        //    // 
        //    // btnCancel
        //    // 
        //    this.btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Right;
        //    this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        //    this.btnCancel.DownImage = global::VAdvantage.Properties.Resources.cancel_down;
        //    this.btnCancel.HoverImage = null;
        //    this.btnCancel.Location = new System.Drawing.Point(541, 3);
        //    this.btnCancel.Name = "btnCancel";
        //    this.btnCancel.NormalImage = global::VAdvantage.Properties.Resources.cancel_up;
        //    this.btnCancel.Size = new System.Drawing.Size(56, 37);
        //    this.btnCancel.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
        //    this.btnCancel.TabIndex = 20;
        //    this.btnCancel.TabStop = false;
        //    this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
        //    // 
        //    // btnok
        //    // 
        //    this.btnok.Anchor = System.Windows.Forms.AnchorStyles.Right;
        //    this.btnok.DialogResult = System.Windows.Forms.DialogResult.OK;
        //    this.btnok.DownImage = global::VAdvantage.Properties.Resources.right_down;
        //    this.btnok.HoverImage = null;
        //    this.btnok.Location = new System.Drawing.Point(603, 3);
        //    this.btnok.Name = "btnok";
        //    this.btnok.NormalImage = global::VAdvantage.Properties.Resources.right_up;
        //    this.btnok.Size = new System.Drawing.Size(56, 37);
        //    this.btnok.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
        //    this.btnok.TabIndex = 19;
        //    this.btnok.TabStop = false;
        //    this.btnok.Click += new System.EventHandler(this.btnok_Click);
        //    // 
        //    // tbplMain
        //    // 
        //    this.tbplMain.BackColor = System.Drawing.Color.White;
        //    this.tbplMain.ColumnCount = 1;
        //    this.tbplMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        //    this.tbplMain.Dock = System.Windows.Forms.DockStyle.Fill;
        //    this.tbplMain.Location = new System.Drawing.Point(0, 27);
        //    this.tbplMain.Name = "tbplMain";
        //    this.tbplMain.RowCount = 2;
        //    this.tbplMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
        //    this.tbplMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
        //    this.tbplMain.Size = new System.Drawing.Size(664, 322);
        //    this.tbplMain.TabIndex = 2;
        //    // 
        //    // PAttributeInstance
        //    // 
        //    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        //    this.ClientSize = new System.Drawing.Size(664, 394);
        //    this.Controls.Add(this.tbplMain);
        //    this.Controls.Add(this.pnlbottum);
        //    this.Name = "PAttributeInstance";
        //    this.Controls.SetChildIndex(this.pnlbottum, 0);
        //    this.Controls.SetChildIndex(this.tbplMain, 0);
        //    this.pnlbottum.ResumeLayout(false);
        //    this.tbplBottum.ResumeLayout(false);
        //    ((System.ComponentModel.ISupportInitialize)(this.btnCancel)).EndInit();
        //    ((System.ComponentModel.ISupportInitialize)(this.btnok)).EndInit();
        //    this.ResumeLayout(false);

        //}

        /// <summary>
        /// Ok button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnok_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }


        /// <summary>
        /// Cancel Button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            //base.Dispose();
            _M_AttributeSetInstance_ID = -1;
            _M_AttributeSetInstanceName = null;
            this.DialogResult = false;
        }

        private void vdgvRecords_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //try
            //{
            //    //int index = vdgvRecords.SelectedRows[0].Index;
            //    int index = vdgvRecords.SelectedIndex;
            //}
            //catch { }
            //EnableButtons();
        }

        private void vdgvRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                //int index = vdgvRecords.SelectedRows[0].Index;
                int index = vdgvRecords.SelectedIndex;
            }
            catch { }
            EnableButtons();

        }




    }
}

